<template>
  <div class="device-tree-table">
    <!-- 顶部搜索 -->
    <AssessmentDialog
      v-model:visible="dialogVisible"
      :mode="dialogMode"
      :rowData="currentRow"
      @success="loadAllDevices"
    />
    <SearchFilters @search="onSearch" />

    <!-- 树形表格 -->
    <el-table
      v-if="treeRows.length"
      :data="treeRows"
      row-key="id"
      :tree-props="{ children: 'children' }"
      border
      height="600"
      style="width: 100%"
    >
      <!-- 设备名称 -->
      <el-table-column prop="name" label="设备名称" min-width="200" />

      <!-- 备件编码 -->
      <el-table-column label="备件编码" width="150">
        <template #default="{ row }">
          <el-input v-model="row.code" placeholder="请输入编码"  />
        </template>
      </el-table-column>

      <!-- 备件名称 -->
      <el-table-column label="备件名称" width="180">
        <template #default="{ row }">
          <el-input v-model="row.name" placeholder="请输入名称" />
        </template>
      </el-table-column>

      <!-- 备件分类 -->
      <el-table-column label="备件分类" width="140">
        <template #default="{ row }">
          <el-select v-model="row.spareClass" placeholder="请选择分类"  >
            <el-option :value="0" label="部件" />
            <el-option :value="1" label="零件" />
          </el-select>
        </template>
      </el-table-column>

      <!-- 金额 -->
      <el-table-column label="金额" width="120">
        <template #default="{ row }">
          <el-input-number v-model="row.amount" :min="0"  />
        </template>
      </el-table-column>

      <!-- 厂商 -->
      <el-table-column label="厂商" width="160">
        <template #default="{ row }">
          <el-input v-model="row.vendor" placeholder="请输入厂商"  />
        </template>
      </el-table-column>

      <!-- 规格 -->
      <el-table-column label="规格" width="160">
        <template #default="{ row }">
          <el-input v-model="row.spec" placeholder="请输入规格"  />
        </template>
      </el-table-column>

      <!-- 材质 -->
      <el-table-column label="材质" width="140">
        <template #default="{ row }">
          <el-input v-model="row.material" placeholder="请输入材质"  />
        </template>
      </el-table-column>

      <!-- 类型 -->
      <el-table-column prop="nodeType" label="类型" width="100">
        <template #default="{ row }">
          <el-tag size="small" :type="tagType(row.nodeType)">
            {{ typeLabel(row.nodeType) }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button  type="success" link size="small" @click="saveRow(row)">
            保存
          </el-button>
          <el-button type="warning" link size="small" @click="clearRow(row)">
            清空
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <el-empty v-else description="暂无数据" class="empty-block" />

    <!-- 分页 -->
    <div class="tree-pagination" v-if="totalRoots > pageSize">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper, sizes"
        :total="totalRoots"
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5,10,20,50]"
        @current-change="noop"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import SearchFilters from './SearchFilters.vue'
import { listSbtz } from '@/api/sbtz/sbtz'
import AssessmentDialog from '@/components/sbtz/assessment/AssessmentDialog.vue'

/** 分页与状态管理 */
const allRoots = ref([])
const fullData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const totalRoots = ref(0)
const dialogVisible = ref(false)
const dialogMode = ref('add')
const currentRow = ref({})

/** 类型映射 */
function typeLabel(type) {
  const map = {
    SYSTEM: '系统',
    MACHINE: '母设备',
    MODULE: '子设备',
    COMPONENT: '部件',
    PART: '零件',
    SPARE: '备件',
  }
  return map[type] || '备件'
}
function tagType(type) {
  return {
    MACHINE: 'primary',
    MODULE: 'success',
    COMPONENT: 'info',
    PART: 'warning',
    SPARE: 'danger',
  }[type] || 'default'
}

/** 初始化加载完整数据 */
async function loadAllDevices() {
  const { rows = [] } = await listSbtz({ pageNum: 1, pageSize: 5000 })
  const filtered = rows.filter(r => r.nodeType !== 'SYSTEM')
  const map = new Map()
  filtered.forEach(f => map.set(f.id, { ...f, children: [] }))
  const roots = []
  filtered.forEach(f => {
    const cur = map.get(f.id)
    if (!f.parentId || !map.has(f.parentId)) roots.push(cur)
    else map.get(f.parentId).children.push(cur)
  })
  roots.forEach(d => attachRealSpares(d))
  fullData.value = roots
  allRoots.value = roots
  totalRoots.value = roots.length
}


function clearRow(row) {
  Object.assign(row, {
    code: '', 
    spareClass: null,
    amount: 0,
    vendor: '',
    spec: '',
    material: '',
  })
  ElMessage.success(`已清空该行`)
}


/** 兼容 spareInfos → 转为子节点 */
function attachRealSpares(node) {
  if (!node) return
  node.children = Array.isArray(node.children) ? node.children : []
  const spares = Array.isArray(node.spareInfos) ? node.spareInfos : []
  spares.forEach((s, idx) => {
    node.children.push({
      id: `spare:${node.id}:${s.id ?? idx}`,
      ...s,
      nodeType: 'SPARE',
      spareClass: s.spareClass ?? 1,
      amount: s.amount ?? 0,
      vendor: s.vendor ?? '',
      spec: s.spec ?? '',
      assetId: node.id,
    })
  })
  node.children.forEach(ch => {
    if (ch.nodeType !== 'SPARE') attachRealSpares(ch)
  })
}

/** 行内保存 */
function saveRow(row) {
  if (!row.name?.trim() || !row.code?.trim()) {
    return ElMessage.warning('请填写完整的编码和名称')
  }
  console.log('保存行：', row)
  ElMessage.success(`已保存 ${row.name}`)
}
function deleteRow(row) {
  console.log('删除行', row)
  ElMessage.success(`已删除 ${row.name}`)
}

/** 搜索逻辑保持原样 */
async function onSearch(params) {
  if (!params.muName && !params.keyword) {
    allRoots.value = fullData.value
    totalRoots.value = allRoots.value.length
    return
  }
  const { rows: matched = [] } = await listSbtz({
    id: params.muName || null,
    keyword: params.keyword || null,
    pageNum: 1,
    pageSize: 1000
  })
  if (!matched.length) {
    allRoots.value = []
    totalRoots.value = 0
    return
  }
  const { rows: all = [] } = await listSbtz({ pageNum: 1, pageSize: 5000 })
  const allFiltered = all.filter(r => r.nodeType !== 'SYSTEM')
  const idSet = new Set()
  const result = []
  function addNodeById(id) {
    if (idSet.has(id)) return
    const node = allFiltered.find(n => n.id === id)
    if (!node) return
    idSet.add(id)
    result.push(node)
    allFiltered.filter(n => n.parentId === id).forEach(ch => addNodeById(ch.id))
  }
  matched.forEach(root => addNodeById(root.id))
  allRoots.value = buildTree(result)
  totalRoots.value = allRoots.value.length
  pageNum.value = 1
}
function buildTree(rows = []) {
  const filtered = rows.filter(r => r.nodeType !== 'SYSTEM')
  const map = new Map()
  filtered.forEach(f => map.set(f.id, { ...f, children: [] }))
  const roots = []
  filtered.forEach(f => {
    const cur = map.get(f.id)
    if (!f.parentId || !map.has(f.parentId)) roots.push(cur)
    else map.get(f.parentId).children.push(cur)
  })
  roots.forEach(d => attachRealSpares(d))
  return roots
}

/** 分页 */
const treeRows = computed(() => {
  const start = (pageNum.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allRoots.value.slice(start, end)
})
function handleSizeChange() { pageNum.value = 1 }
function noop() {}

onMounted(() => loadAllDevices())
</script>

<style scoped>
.device-tree-table {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 10px 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.tree-pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
.empty-block {
  height: 600px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.el-input,
.el-input-number,
.el-select {
  width: 100%;
}
</style>
